package online.yysh.charging;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatDialog;
import androidx.lifecycle.Observer;

import com.google.gson.Gson;

import online.yysh.charging.base.BaseActivity;
import online.yysh.charging.bean.Login;
import online.yysh.charging.bean.PreOrder;
import online.yysh.charging.bean.request.GetPreOrderRequest;
import online.yysh.charging.bean.response.GetPreOrderResponse;
import online.yysh.charging.inputfilter.CashierInputFilter;
import online.yysh.charging.livedata.UserManager;
import online.yysh.charging.utils.HttpUtil;
import online.yysh.charging.wxapi.WXConstant;

import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 我的余额，以及充值都在这里
 */
public class BalanceActivity extends BaseActivity implements View.OnClickListener {

    private TextView tv_title, tv_balance, tv_cancel, tv_recharge_record;
    private EditText et_money;
    private ImageView iv_show;

    private boolean showStatus = true;
    private String myMoney;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_balance;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tv_recharge_record = findViewById(R.id.tv_diy);
        tv_recharge_record.setOnClickListener(this);
        iv_show = findViewById(R.id.iv_show);
        iv_show.setOnClickListener(this);
        et_money = findViewById(R.id.et_money);
        et_money.setFilters(new InputFilter[]{new CashierInputFilter()});
        tv_balance = findViewById(R.id.tv_balance);
        tv_balance.setText(R.string.wallet);
        tv_title = findViewById(R.id.tv_title);
        tv_cancel = findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        tv_title.setText(R.string.wallet);
        tv_recharge_record.setText(R.string.recharge_history);
        UserManager.getInstance().getLiveData().observe(this, new Observer<Login>() {
            @Override
            public void onChanged(Login login) {
                myMoney = "账户余额：" + login.getMoney() + "元";
                tv_balance.setText(myMoney);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_cancel:
                finish();
                break;
            case R.id.iv_show:
                if (showStatus) {
                    tv_balance.setText("账户余额：********");
                    showStatus = false;
                    iv_show.setBackgroundResource(R.mipmap.invisible);
                } else {
                    tv_balance.setText(myMoney);
                    showStatus = true;
                    iv_show.setBackgroundResource(R.mipmap.visible);
                }
                break;
            case R.id.tv_diy:
                //进入充值记录页面
                startActivity(new Intent(this, RechargeRecordActivity.class));
                break;
        }
    }


    public void selectPayMode(View view) {
        String money = et_money.getText().toString().trim();
        if (!TextUtils.isEmpty(money)) {
            String m = Float.valueOf(money) * 100 + "";
            showSelectApplyModeDialog(Integer.parseInt(m.substring(0, m.indexOf("."))));
        } else {
            Toast.makeText(this, "充值金额不能为空", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 微信支付
     * 1.向后台请求，后台返回必须参数数据
     * 2.请求微信支付
     * 3.处理结果
     */
    private void wxPay(int money) {

        HttpUtil.getInstance().getPreOrder(new GetPreOrderRequest(openid, money), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e(TAG, "getPreOrder: " + result);
                GetPreOrderResponse data = new Gson().fromJson(result, GetPreOrderResponse.class);
                if ("ok".equals(data.getStatus())) {
                    PreOrder order = data.getData();

                    IWXAPI wxapi = WXAPIFactory.createWXAPI(BalanceActivity.this, WXConstant.WX_APP_ID);  //应用ID 即微信开放平台审核通过的应用APPID
                    wxapi.registerApp(WXConstant.WX_APP_ID);    //应用ID
                    PayReq payReq = new PayReq();
                    payReq.appId = order.getAPPID();        //应用ID
                    payReq.partnerId = WXConstant.WX_PARTNER_ID;      //商户号 即微信支付分配的商户号
                    payReq.prepayId = order.getPREPAYID();        //预支付交易会话ID
//                    payReq.packageValue = order.getPACKAGE();    //扩展字段Sign=WXPay
                    payReq.packageValue = order.getPACKAGE();    //扩展字段
                    payReq.nonceStr = order.getNONCESTR();        //随机字符串不长于32位。
                    payReq.timeStamp = "" + order.getTIMESTAMP(); //时间戳
                    payReq.sign = order.getSIGN();             //签名
                    wxapi.sendReq(payReq);
                }
            }
        });
    }

    /**
     *  选择支付方式
     */
    public void showSelectApplyModeDialog(final int money) {
        final AppCompatDialog appCompatDialog = new AppCompatDialog(this);
        View view = getLayoutInflater().inflate(R.layout.dialog_recharge, null);
        TextView tv_title = view.findViewById(R.id.tv_title);
        tv_title.setText("选择支付方式");
        LinearLayout ll_money = view.findViewById(R.id.ll_money);
        ll_money.setVisibility(View.GONE);
        TextView tv_cancel = view.findViewById(R.id.tv_cancel);
        tv_cancel.setText("微信支付");
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wxPay(money);
                appCompatDialog.dismiss();
            }
        });
        TextView tv_confirm = view.findViewById(R.id.tv_confirm);
        tv_confirm.setText("支付宝支付");
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showToast("该功能正在开发中，敬请期待");
                appCompatDialog.dismiss();
            }
        });
        appCompatDialog.setContentView(view);
        Window window = appCompatDialog.getWindow();
        window.setBackgroundDrawableResource(R.color.transparent);
        window.setGravity(Gravity.CENTER);
        window.setLayout(700, ViewGroup.LayoutParams.WRAP_CONTENT);
        appCompatDialog.show();
    }
}
